<template>
  <view>
    <text v-if="disabled">{{ supplierName }}</text>
    <uni-data-select
      v-else
      v-model="props.supplierId"
      :localdata="supplierOptions"
      @change="handleChange"
    ></uni-data-select>
  </view>
</template>

<script setup lang="ts">
import {usePmSupplierApi} from "@/api/pm/resource/supplier";

defineOptions({ name: 'PmCustomSelect' })

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  supplierId: {
    type: [String, Number, Array<string | number>],
    default: null,
  },
})

const supplierName = computed(() => {
  const list = toRaw(allSupplierList.value);
  if (!props.supplierId || !list || !list.length) {
    return '暂无';
  } else {
    const customList = Array.isArray(props.supplierId) ? props.supplierId : [props.supplierId]
    const resUser = list.filter((u: PmSupplierForm) => customList.includes(u.id));
    if (resUser) {
      const resUserName = resUser.map(custom => {
        return custom.supplierName
      })
      return resUserName.join(',');
    }
    return `未知（${props.supplierId}）`;
  }
})


type SupplierOption = {
  value: string | number,
  text: string,
}
const supplierOptions = ref<SupplierOption[]>([]);

function getOptions() {
  const list = toRaw(allSupplierList.value);
  if (list && list.length) {
    supplierOptions.value = list.map((c: PmSupplierForm) => {
      return {
        value: c.id,
        text: c.supplierName,
      };
    });
  } else {
    supplierOptions.value = [];
  }
}

const $emit = defineEmits(['update:supplierId']);
function handleChange(val: string) {
  $emit('update:supplierId', val);
}

const allSupplierList = ref<PmSupplierForm[]>([]);
function getAllOptList() {
  usePmSupplierApi().getAllSupplierList().then((res) => {
    if (res.code === 0 && res.data) {
      allSupplierList.value = res.data;
      getOptions();
    }
  })
}

onLoad(() => {
  getAllOptList();
})
</script>

<style scoped lang="scss">

</style>
